package com.clx;


import com.clx.channelHandler.ConsumerChannelInitializer;
import com.clx.channelHandler.hander.MySimpleChannelInboundHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import lombok.extern.slf4j.Slf4j;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.serialization.ObjectDecoder;


/**
 * 提供boosstrop单例
 * todo: 这里会有什么问题
 * */
@Slf4j
public class NettyBootstrapInitializer {

    private static final Bootstrap bootstrap = new Bootstrap();

    static {
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                // 选择初始化一个什么样的channel，Channel是 Netty 对 “网络连接” 的抽象，。
                .channel(NioSocketChannel.class)
                .handler(new ConsumerChannelInitializer());
    }

    private NettyBootstrapInitializer(){

    }

    public static Bootstrap getBootstrap(){

            return bootstrap;
    }
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline()
                // ① 添加 Object 编码器（发送时序列化）
                .addLast(new ObjectEncoder())
                // ② 添加 Object 解码器（接收时反序列化，最大字节限制为 Integer.MAX_VALUE，类解析器为缓存禁用）
                .addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)))
                .addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf msg) throws Exception {
                        log.info("msg-->{}", msg.toString());
                    }
                });
    }


}
